package com.javen.demo;


import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

class MyTask extends RecursiveTask<Integer> {
    private final static Integer JUST_VALUE = 10;
    private static final long serialVersionUID = -1283397432054371763L;
    private final int begin;
    private final int end;
    private int result;

    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if ((end - begin) <= JUST_VALUE) {
            for (int i = begin; i <= end; i++) {
                result = result + i;
            }
        } else {
            int middle = (end + begin) / 2;
            MyTask task = new MyTask(begin, middle);
            MyTask task2 = new MyTask(middle + 1, end);
            task.fork();
            task2.fork();
            result = task.join() + task2.join();
        }
        return result;
    }
}

@Slf4j
public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask task = new MyTask(0, 100);

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(task);
        log.info("计算结果 {}", forkJoinTask.get());
        forkJoinPool.shutdown();

        CompletableFuture.runAsync(() -> {
            log.info("xxx");
        });

        // CompletableFuture 示例
        CompletableFuture<String> exceptionally = CompletableFuture
                .supplyAsync(() -> {
                            int i = 10 / 0;
                            return "IJPay";
                        }
                )
                .whenComplete((t, e) -> {
                    log.info("t: {} e:{}", t, e);
                })
                .exceptionally(e -> {
                    log.info("ERROR {}", e.getMessage());
                    return "ERROR";
                });
        log.info("get {}", exceptionally.get());
    }
}
